<?php
/**
 * <b>RUBIK IT Solution & Development ltd.</b>
 *
 * PROJECT		: Rubik Ultimate Framework
 * @version 	: 1.1
 * COPYRIGHT    : 2008
 * ------------------------------------------------------
 * 
 * Created on	:  Jun 15, 2008
 * 
 */

// no direct access
defined ( '_FW_EXEC' ) or die ( 'Restricted access' );
RCoreImporter::cls( "helper.RFileFolderHelper" );
RCoreImporter::cls( "module.ModulePositionManager" );

class SysTemplate {
	
	/**
	 * Get Instance
	 *
	 * @return SiteTemplate
	 */
	static function &getInstance() {
		static $instance;
		if (empty ( $instance )) {
			$instance = new SiteTemplate ( SysTemplate::getTemplate () );
		}
		return $instance;
	}
	
	/**
	 * Instance of pagination class
	 *
	 * @param int $totalItems total item of page
	 * @param int $recordPerPage how many record per page
	 * @param string $link 
	 * @return BasePagination
	 */
	static function &getPaginationInstance($totalItems, $recordPerPage = 10, $link = '?page') {
//		static $instances;
//		
//		if (! isset ( $instances )) {
			$path = SYS_CUR_TMPL_PATH . 'html' . DS . 'pagination.php';
			if (file_exists ( $path )) {
				require_once ($path);
				$instances = new Pagination ( $totalItems, $recordPerPage, $link );
			} else {
				RCoreImporter::cls( "html.BasePagination" );
				$instances = new BasePagination ( $totalItems, $recordPerPage, $link );
			}
//		}
		
		return $instances;
	}
	/**
	 * Get Instance of Menu
	 *
	 * @param string $alias
	 * @return BaseMenu of Menu class
	 */
	static function &getMenuInstance($alias) {
		static $menu;
		if (! isset ( $menu )) {
			$menu = array ();
		}
		if (empty ( $menu [$alias] )) {
			$path = SYS_CUR_TMPL_PATH . 'html' . DS . 'menu.php';
			if (! file_exists ( $path ))
				$path = SYS_TMPL_PATH . 'system' . DS . 'html' . DS . 'menu.php';
			
			if (file_exists ( $path )) {
				require_once ($path);
				$menu [$alias] = new Menu ( );
			} else {
				RCoreImporter::cls( "html.BaseMenu" );
				$menu [$alias] = new BaseMenu ( );
			}
		}
		return $menu [$alias];
	}
	
	/**
	 * Get the template string that has been filled up with the data 
	 *
	 * @param string $tmplFile
	 * @param string $app if empty -> get system application
	 * 
	 * @return string template string that has been filled up with the data. 
	 */
	static function getAppTemplate($tmplFile, $app = null) {
		$instance = SysTemplate::getInstance ();
		return $instance->getAppTemplate ( $tmplFile, $app );
	}
	
	/**
	 * Echo the template string that has been filled up with the data 
	 *
	 * @param string $tmplFile
	 * @param string $app if empty -> get system application
	 */
	static function printAppTemplate($tmplFile, $app = null) {
		echo SysTemplate::getAppTemplate ( $tmplFile, $app );
	}
	
	/**
	 * Get the template string that has been filled up with the data 
	 *
	 * @param string $tmplFile
	 * @param string $mod module
	 * 
	 * @return string template string that has been filled up with the data. 
	 */
	static function loadModuleTemplate($tplPath, $modName) {
		$modPath = SYS_MOD_PATH . $modName . DS;
		return SysTemplate::loadTemplate ( $tplPath, $modPath );
	}
	
	/**
	 * Load Module CSS Files
	 *
	 * @param string $cssPath path to css file.
	 */
	static function loadModuleCSS($cssPath, $modName) {
		$modPath = SYS_MOD_PATH . $modName . DS;
		$modUrl = SYS_MOD_URL . $modName . '/';
		
		return SysTemplate::_loadCSS ( $cssPath, $modPath, $modUrl );
	}
	
	/**
	 * Load Application Javascript Files
	 *
	 * @param string $jsPath path to javascript file
	 */
	static function loadModuleJS($jsPath, $modName) {
		$modPath = SYS_MOD_PATH . $modName . DS;
		$modUrl = SYS_MOD_URL . $modName . '/';
		return SysTemplate::_loadJS ( $jsPath, $modPath, $modUrl );
	}
	
	/**
	 * Echo the template string that has been filled up with the data 
	 *
	 * @param string $tmplFile
	 * @param string $mod Moldule
	 */
	static function printModuleTemplate($tmplFile, $mod) {
		echo SysTemplate::getModuleTemplate ( $tmplFile, $mod );
	}
	
	/**
	 * Include the site template and run it
	 * WARNING: this static function should be call at the end of index for 
	 * 		printing the template and view it to the real life
	 * 
	 */
	static function runSiteTemplate() {
		// add all css files in css folder of current template into SysResponse
		//ex: SysResponse::addStyleSheetFile(SYS_CUR_TMPL_URL."css/master.css");
		

		SysTemplate::loadAllCssOfTemplate ();
		
		// add all javascript files in js folder of current template into SysResponse
		//ex: SysResponse::addJavascriptFile(SYS_CUR_TMPL_URL."js/main.js");
		SysTemplate::loadAllJsOfTemplate ();
		$fileIndex = SYS_CUR_TMPL_PATH . "index.php";
		if (! file_exists ( $fileIndex ))
			$fileIndex = SYS_TMPL_PATH . "system" . DS . "index.php";
		include ($fileIndex);
	}
	
	/**
	 * Get the content of all module at a postion
	 *
	 * @param string $position
	 * 
	 * @return string the HTML of all module at a position
	 */
	static function getMoldulePosition($position) {
		$module = new ModulePositionManager ( $position );
		$module->showModules ();
	}
	
	/**
	 * Load Application Template Files
	 *
	 * @param string $classPath class path. if it's "front/view", system will load "front/view.tpl.html"
	 * 
	 */
	static function loadAppTemplate($tplPath, $appName = null, $tplExt = ".tpl.html") {
		if (empty ( $appName )) {
			$appName = SystemSite::getApplicationName();
		}
		$app = SYS_APP_PATH . $appName . DS;
		return SysTemplate::loadTemplate ( $tplPath, $app , $tplExt);
	}
	
	/**
	 * get Application Template Files Paht
	 *
	 * @param string $classPath class path. if it's "front/view", system will load "front/view.tpl.html"
	 * 
	 */
	static function getAppTemplatePath($tplPath, $appName = null, $tplExt = ".tpl.html") {
		if (empty ( $appName )) {
			$appName = SystemSite::getApplicationName();
		}
		$app = SYS_APP_PATH . $appName . DS;
		return SysTemplate::getTemplatePath( $tplPath, $app , $tplExt);
	}
	
	/**
	 * Load Application CSS Files
	 *
	 * @param string $classPath path to CSS file
	 */
	static function loadAppCSS($cssPath, $appName = null) {
		if (empty ( $appName )) {
			$appName = SystemSite::getApplicationName();
		} 
		$appPath = SYS_APP_PATH . $appName . DS;
		$appUrl = SYS_APP_URL . $appName . '/';
		return SysTemplate::_loadCSS ( $cssPath, $appPath, $appUrl );
	}
	
	/**
	 * Load Application Javascript Files
	 *
	 * @param string $classPath class path. it should be informat: "package.ClassName"
	 */
	static function loadAppJS($jsPath, $appName = null) {
		if (empty ( $appName )) {
			$appName = SystemSite::getApplicationName();
		} 
		$appPath = SYS_APP_PATH . $appName;
		$appUrl = SYS_APP_URL . $appName;
		return SysTemplate::_loadJS ( $jsPath, $appPath, $appUrl );
	}
	
	/**
	 * Load Template Files
	 *
	 * @param string $tplPath tpl path
	 * @param string $path to Folder parent of Templates Folder
	 * @param string $tplExt template extends
	 */
	static function loadTemplate($tplPath, $path, $tplExt = ".tpl.html") {
		$path .= "templates" . DS;
		$tplPath .= $tplExt;
		$tmplPath = SysTemplate::_getExpectedPath ( $tplPath, $path );
		if ($tmplPath === false) {
			RError::raiseError ( 300, "The template path: <b>$tplPath</b> in doesn't exist in folder: <b>$path</b>" );
		}
		return SysTemplate::loadTemplateContent ( "{$path}{$tmplPath}" );
	}
	
	/**
	 * Get Template File path
	 *
	 * @param string $tplPath tpl path
	 * @param string $path to Folder parent of Templates Folder
	 * @param string $tplExt template extends
	 */
	static function getTemplatePath($tplPath, $path, $tplExt = ".tpl.html") {
		$path .= "templates" . DS;
		$tplPath .= $tplExt;
		$tmplPath = SysTemplate::_getExpectedPath ( $tplPath, $path );
		if ($tmplPath === false) {
			RError::raiseError ( 300, "The template path: <b>$tplPath</b> in doesn't exist in folder: <b>$path</b>" );
		}
		return "{$path}{$tmplPath}";
	}
	
	/**
	 * Load a template at exactly path
	 *
	 * @param string $filePath template file path
	 * @return string the content of template file
	 */
	static function loadTemplateContent($filePath) {
		return addcslashes ( file_get_contents ( $filePath ), "\\\"" );
	}
	
	/**
	 * Load CSS Files
	 *
	 * @param string $classPath class path. it should be informat: "package.ClassName"
	 * @param string $path path to Folder parent of Templates Folder
	 * @param string $url url to Folder parent of Templates Folder
	 * 
	 */
	static protected function _loadCSS($cssPath, $path, $url) {
		$path .= "templates/";
		$url .= "templates/";
		$expectedPath = SysTemplate::_getExpectedPath ( $cssPath, $path );
		if ($expectedPath === false) {
			return false;
		}
		
		$expectedPath = $url . $expectedPath;
		SysResponse::addStyleSheetFile ( $expectedPath );
		return $expectedPath;
	}
	
	/**
	 * Load Javascript Files
	 *
	 * @param string $jsPath javascript file path. it should be informat: "package/ClassName"
	 * @param string $path path to Folder parent of Templates Folder
	 * @param string $url url to Folder parent of Templates Folder
	 * 
	 */
	static protected function _loadJS($jsPath, $path, $url) {
		$path .= "templates/";
		$url .= "templates/";
		$expectedPath = SysTemplate::_getExpectedPath ( $jsPath, $path );
		if ($expectedPath === false) {
			return false;
		}
		
		$expectedPath = $url . $expectedPath;
		SysResponse::addJavascriptFile ( $expectedPath );
		return $expectedPath;
	}
	
	/**
	 * Retry the expected template
	 *
	 * @param string $filePath the file path inside the template
	 * @param string $path the path to the root of template (don't include template file)
	 * @return string or false Template name or false
	 */
	static protected function _getExpectedTemplate($filePath, $path) {
		$tmpName = SystemSite::getTemplate ();
		$testPath = $path . SystemSite::getTemplate () . "/" . $filePath;
		
		if (file_exists ( $testPath )) {
			return SystemSite::getTemplate ();
		}
		
		$testPath = $path . "default/" . $filePath;
		if (file_exists ( $testPath )) {
			return "default";
		}
		return false;
	}
	
	/**
	 * Get expected path (from the root url) for a file depending on the template.
	 *
	 * @param string $filePath file path inside the template path
	 * @param string $path file path to the root of template folder
	 * @return string the path from the template root to expected file
	 */
	static protected function _getExpectedPath($filePath, $path) {
		
		// Change the path into URL path
		$filePath = str_replace ( "\\", "/", $filePath );
		
		// check for mobile
		if (SysRequest::isMobile ()) {
			$testPath = $path . "mobile/";
			$template = SysTemplate::_getExpectedTemplate ( $filePath, $testPath );
			if ($template !== false) {
				return "mobile/$template/$filePath/";
			}
		}
		
		$testPath = $path;
		$template = SysTemplate::_getExpectedTemplate ( $filePath, $testPath );
		if ($template !== false) {
			return "{$template}/{$filePath}";
		}
		
		return false;
	}
	
	/**
	 * Load All CSS File of Template
	 *
	 */
	static function loadAllCssOfTemplate() {
		$cssFiles = array ();
		$cssFiles = RFileFolderHelper::files ( SYS_CUR_TMPL_PATH . 'css', 'css', 3, true );
		$url = SYS_CUR_TMPL_URL;
		
		if (! empty ( $cssFiles )) {
			foreach ( $cssFiles as $cssFile ) {
				$name = explode ( DS, $cssFile );
				$folderName = $name [count ( $name ) - 2];
				$fileName = $name [count ( $name ) - 1];
				
				if ($folderName == 'css') {
					$cssFile = $url . $folderName . '/' . $fileName;
					SysResponse::addStyleSheetFile ( $cssFile );
				} else {
					$cssFile = $url . 'css/' . $folderName . '/' . $fileName;
					SysResponse::addStyleSheetFile ( $cssFile, $folderName );
				}
			}
		}
	}
	
	/**
	 * Load All CSS File of Template
	 *
	 */
	static function loadTemplateStyle($filePathFromStyle, $media = null) {
		SysResponse::addStyleSheetFile ( SYS_CUR_TMPL_URL . "style/" . $filePathFromStyle, $media );
	}
	
	/**
	 * Load All JS Files of Template
	 *
	 */
	static function loadAllJsOfTemplate() {
		$jsFiles = array ();
		$jsFiles = RFileFolderHelper::files ( SYS_CUR_TMPL_PATH . 'js', 'js', false, false );
		
		if (! empty ( $jsFiles )) {
			foreach ( $jsFiles as $jsFile ) {
				$jsFile = SYS_CUR_TMPL_URL . 'js/' . $jsFile;
				SysResponse::addJavascriptFile ( $jsFile );
			}
		}
	}
	
	/**
	 * Get the template name of site
	 *
	 * @return string
	 */
	static function getTemplate() {
		static $template;
		if (! empty ( $template )) {
			return $template;
		}
		
		// Checking for the request.
		// If we have tmpl --> that is the applied template
		$template = $_REQUEST ['tmpl'];
		
		$templatePath = SYS_TMPL_PATH;
		if (SysRequest::isMobile () && SysTemplate::isExistMobileTpl ()) {
			$templatePath .= "mobile";
		}
		$listTemplate = RFileFolderHelper::folders ( $templatePath, '.', false );
		
		if (! in_array ( $template, $listTemplate )) {
			if ($template) {
				RError::raiseWarning ( 300, "Template name: '$template' doesn't exist." );
			}
			
			$config = SystemSite::getSiteConfig ();
			$template = $config->tempalte;
		}
		if (! in_array ( $template, $listTemplate )) {
			if ($template) {
				RError::raiseWarning ( 300, "Template name: '$template' doesn't exist." );
			}
			$template = "system";
		}
		return $template;
	}
	
	/**
	 * Check if mobile template is exist or not.
	 *
	 * @return boolean
	 */
	static function isExistMobileTpl() {
		$testPath = SYS_TMPL_PATH . "mobile";
		return file_exists ( $testPath );
	}

}
?>
